package org.finesys.chat.core.base.document.loader;

import org.apache.commons.io.IOUtils;
import org.finesys.chat.core.base.document.Document;
import org.finesys.chat.core.base.document.source.DocumentSource;
import org.finesys.chat.core.base.document.parser.DocumentParser;

import java.io.IOException;
import java.io.InputStream;

public class DocumentLoader {

    public static Document load(DocumentSource documentSource, DocumentParser documentParser) {
        InputStream inputStream = null;
        try {
            inputStream = documentSource.inputStream();
            Document document = documentParser.parse(inputStream);
            documentSource.metadata().asMap().forEach((key, value) -> document.getMetadata().put(key, value));
            return document;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                IOUtils.closeQuietly(inputStream);
            }
        }

    }
}
